package com.tywj.panda.driver.details

import android.annotation.SuppressLint
import android.graphics.BitmapFactory
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import com.alibaba.android.arouter.facade.annotation.Route
import com.amap.api.maps.AMap
import com.amap.api.maps.model.*
import com.amap.api.navi.AmapNaviPage
import com.amap.api.navi.AmapNaviParams
import com.amap.api.navi.AmapNaviType
import com.amap.api.navi.AmapPageType
import com.amap.api.services.core.AMapException
import com.amap.api.services.core.LatLonPoint
import com.amap.api.services.route.*
import com.amap.api.services.route.RouteSearch.DRIVING_SINGLE_DEFAULT
import com.tywj.lib.core.common.util.LogUtil
import com.tywj.lib.location.entity.LocationEntity
import com.tywj.lib.route.RouteParam
import com.tywj.lib.route.RouteUtil
import com.tywj.navigation.base.BaseMapFragment
import com.tywj.navigation.entity.DrivingRouteOverlay
import com.tywj.navigation.popupwindow.MapDetailsPopUpImgView
import com.tywj.navigation.popupwindow.NavigationPopupWindow
import com.tywj.navigation.tool.MapTool
import com.tywj.panda.customer.common.entity.HomeLineDetailsEntity
import com.tywj.panda.customer.common.http.PDObjectCallback
import com.tywj.panda.customer.common.provider.IHomeService
import com.tywj.panda.customer.common.tool.PermissionTool
import com.tywj.panda.customer.common.tool.TimeTool
import com.tywj.panda.driver.R
import com.tywj.panda.driver.entity.DriverTaskEntity
import com.tywj.panda.driver.route.DriverRoute
import kotlinx.android.synthetic.main.driver_fragment_route.*


/**
 * <pre>
 *     author : June Yang
 *     time   : 2020/06/22
 *     desc   : 班次详情->行驶详情
 *     version: 2.0.0
 * </pre>
 */
@Route(path = DriverRoute.DRIVER_TASK_ROUTE)
class DriverRouteFragment : BaseMapFragment() {
    override fun getLayoutID(): Int = R.layout.driver_fragment_route

    companion object {
        const val PARAMS_TASK_ENTITY = "id"
    }

    // 是否是第一次获取定位
    private var isFirstLocation = false

    private var id = ""
    private lateinit var bean: DriverTaskEntity.DataBean

    private var routeSearch: RouteSearch? = null

    private var clickMarker: Marker? = null

    //当前位置
    private var currentLocation: LocationEntity? = null


    //站点
    private var stations = ArrayList<HomeLineDetailsEntity.Station>()

    //最终选择的出发起始站点
    private var upStations = ArrayList<HomeLineDetailsEntity.Station>(2)

    //途径点坐标
    private var listRoute = ArrayList<ArrayList<Double>>()

    override fun initVariable(savedInstanceState: Bundle?) {
        super.initVariable(savedInstanceState)

        bean = RouteParam(this).getParcelable(PARAMS_TASK_ENTITY)!!
    }

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)
    }

    override fun initListener() {
        super.initListener()

        map.setInfoWindowAdapter(object : AMap.InfoWindowAdapter {
            var infoWindow: View? = null

            override fun getInfoContents(marker: Marker?): View {
                return View(requireContext())
            }

            override fun getInfoWindow(marker: Marker): View {
                if (infoWindow == null) {
                    infoWindow = LayoutInflater.from(requireContext())
                        .inflate(R.layout.navigation_map_infiwindow_layout, null)
                }

                infoWindow?.let {
                    render(marker, it)
                }
                return infoWindow!!
            }
        })

        map.setOnMarkerClickListener(AMap.OnMarkerClickListener { marker ->
            if (marker.title != null && marker.title != "") {
                clickMarker = marker
                clickMarker?.showInfoWindow()
            }
            true
        })

        map.setOnMapClickListener {
            if (clickMarker != null && clickMarker!!.isInfoWindowShown) {
                clickMarker!!.hideInfoWindow()
                clickMarker = null
            }
        }
    }


    override fun onVisibleFirst() {
        super.onVisibleFirst()

        PermissionTool.location({
            // do nothing
        }, {
            // 没有定位权限，地图显示到成都
            PermissionTool.showOpenLocationToast()
            toLocation(MapTool.LATITUDE_DEFAULT, MapTool.LONGITUDE_DEFAULT, MapTool.ZOOM_LEVEL_DEFAULT)
        })

        loadData(bean)
    }


    private fun loadData(bean: DriverTaskEntity.DataBean) {
        statusLayout.showLoadingLayout()

        RouteUtil.getServiceProvider(IHomeService::class.java)?.getCRMLineDetails(bean.lineCode)
            ?.attachToLifecycle(this)
            ?.execute(object : PDObjectCallback<HomeLineDetailsEntity>(HomeLineDetailsEntity::class.java) {
                override fun success(data: HomeLineDetailsEntity) {
                    statusLayout.showContentLayout()
                    handleData(data)
                }

                override fun error(code: Int, message: String) {
                    super.error(code, message)
                    statusLayout.showErrorLayoutByCode(code, message)
                }
            })
    }

    @SuppressLint("SetTextI18n")
    private fun handleData(data: HomeLineDetailsEntity) {
        tvMileage.text = data.mileage.toString() + "KM"
        tvEndStation.text = data.end.name
        tvStartStation.text = data.start.name
        stations.clear()
        //拼接站点信息
        stations.add(data.start)
        stations.addAll(data.ways)
        stations.add(data.end)

        listRoute = data.route

        upStations.add(stations.first())
        upStations.add(stations.last())

        tvTime.text = totalTime().toString() + "min"

        refreshBusTimeList()

        startRouteSearch()

    }

    override fun onMyLocationChange(location: LocationEntity) {
        super.onMyLocationChange(location)

        if (!isFirstLocation) {
            // 第一次获取定位数据，将地址显示到该位置
            isFirstLocation = true
            currentLocation = location
            currentLocation?.let {
                toLocation(it.latitude, it.longitude, MapTool.ZOOM_LEVEL_DEFAULT)
            }
        }
    }

    private fun totalTime(): Int {
        var totalTime = 0
        stations.forEachIndexed { index, station ->
            for (i in 0..index) {
                if (i == index) {
                    totalTime += station.time
                    break
                }
            }
        }
        return totalTime
    }

    /**
     * 开始路径规划
     * 驾车出行路线规划
     * https://lbs.amap.com/api/android-sdk/guide/route-plan/drive/#t6
     */

    private fun startRouteSearch() {
        //第一步
        routeSearch = RouteSearch(requireActivity())

        /**
         * 第二步
         * 设置数据回调监听器
         * 驾车出行路线规划
         * 高德接口链接：https://lbs.amap.com/api/android-sdk/guide/route-plan/drive
         */
        routeSearch?.setRouteSearchListener(object : RouteSearch.OnRouteSearchListener {
            override fun onBusRouteSearched(busRouteResult: BusRouteResult, i: Int) {

            }

            /**
             * 第五步 接受数据
             *
             *
             */
            override fun onDriveRouteSearched(driveRouteResult: DriveRouteResult, rCode: Int) {

                if (rCode == AMapException.CODE_AMAP_SUCCESS) {
                    if (driveRouteResult.paths != null) {
                        val drivePath = driveRouteResult.paths[0] ?: return
                        val drivingRouteOverlay = DrivingRouteOverlay(
                            requireContext(), map, drivePath,
                            driveRouteResult.startPos,
                            driveRouteResult.targetPos, null, stations.first(), stations.last()
                        )
                        drivingRouteOverlay.setNodeIconVisibility(false) //设置节点marker是否显示
                        drivingRouteOverlay.setIsColorfulline(true) //是否用颜色展示交通拥堵情况，默认true
                        drivingRouteOverlay.removeFromMap()
                        drivingRouteOverlay.addToMap()
                        drivingRouteOverlay.zoomToSpan()
                    }
                } else {
                    shortToast("路径获取失败")
                }

            }

            override fun onWalkRouteSearched(walkRouteResult: WalkRouteResult, i: Int) {}
            override fun onRideRouteSearched(rideRouteResult: RideRouteResult, i: Int) {}
        })


        val start = LatLonPoint(upStations[0].loc.last(), upStations[0].loc.first())
        val end = LatLonPoint(upStations[1].loc.last(), upStations[1].loc.first())

        val fromAndTo = RouteSearch.FromAndTo(start, end)

        val latLonPoints: MutableList<LatLonPoint> = ArrayList()

        val markerOption = MarkerOptions()
        markerOption.draggable(false) //设置Marker可拖动

        markerOption.icon(
            BitmapDescriptorFactory.fromBitmap(
                BitmapFactory.decodeResource(resources, R.drawable.jing)
            )
        )
        // 将Marker设置为贴地显示，可以双指下拉地图查看效果
        markerOption.isFlat = true //设置marker平贴地图效果

        for (i in 1 until stations.size - 1) {
            val latLng = LatLng(stations[i].loc[1], stations[i].loc[0])
            markerOption.title(stations[i].name)
            markerOption.snippet("预计到达：" + stations[i].timeAdd + "？" + stations[i].img + "？" + stations[i].info)
            map.addMarker(markerOption.position(latLng))
        }

        //listRoute 二维数组遍历 途径点数据
        listRoute.forEach {
            //注意经纬度的顺序 移动端SDK经纬度的格式为‘纬度,经度’。
            val point = LatLonPoint(it.last(), it.first())
            latLonPoints.add(point)
        }

        /**
         * 第三步
         *设置搜索参数
         * fromAndTo包含路径规划的起点和终点，
         * drivingMode表示驾车模式  //返回的结果会优先考虑高速路，并且会考虑路况躲避拥堵，与高德地图的“躲避拥堵&高速优先”策略一致
         * 第三个参数表示途经点（最多支持16个），第四个参数表示避让区域（最多支持32个），第五个参数表示避让道路
         */
        val query = RouteSearch.DriveRouteQuery(
            fromAndTo,
            DRIVING_SINGLE_DEFAULT,
            latLonPoints,
            null,
            ""
        )
        /**
         * 第四步：发送请求
         */
        routeSearch?.calculateDriveRouteAsyn(query)
    }

    private fun render(marker: Marker, view: View) {
        val time = view.findViewById<TextView>(R.id.time)
        val name = view.findViewById<TextView>(R.id.name)
        val photo = view.findViewById<TextView>(R.id.tvSeeReal)
        val daohang = view.findViewById<TextView>(R.id.tvNavigation)

        val infos = marker.snippet.split("？").toTypedArray()
        time.text = infos[0]
        name.text = marker.title

        photo.setOnClickListener {
            if (marker.title != null && marker.title != "") {

                val path = marker.snippet.split("？").toTypedArray()[1]
                val info = marker.snippet.split("？").toTypedArray()[2]

                LogUtil.d("图片地址:$path")
                if (path.isNotEmpty()) {
                    val mpopUpWindows = MapDetailsPopUpImgView(
                        requireContext(),
                        path,
                        info
                    )
                    mpopUpWindows.show()
                } else {
                    shortToast("暂无站点图片")
                }
            }
        }
        val popupWindow = NavigationPopupWindow(requireContext(), marker.position)

        popupWindow.goHereListener {
            currentLocation?.let {
                toStartNavigation(it, marker.position)
            }

        }
        daohang.setOnClickListener { v ->
            popupWindow.showAtDropDownCenter(v)

        }
    }

    //根据用户选择的班次时刻表 同步显示每站的时间表(stations中处理站点信息的时间点 站点之间需要累加实现总时间)
    private fun refreshBusTimeList() {

        var totalTime = 0

        stations.forEachIndexed { index, station ->
            for (i in 0..index) {
                if (i == index) {
                    totalTime += station.time
                    break
                }
            }
            //发车时间计算
            station.timeAdd = TimeTool.formatTimeAdd(bean.lineTime, totalTime.toString())
        }
    }

    private fun toStartNavigation(start: LocationEntity, end: LatLng) {
        val mStart = Poi("我的位置", LatLng(start.latitude, start.longitude), "")
        val mEnd = Poi("终点位置", LatLng(end.latitude, end.longitude), "")

        AmapNaviPage.getInstance().showRouteActivity(
            context,
            AmapNaviParams(mStart, null, mEnd, AmapNaviType.DRIVER, AmapPageType.NAVI),
            null
        )
    }
}